import React from 'react'
import {Tag, Toast} from 'antd-mobile'
import {get, post} from '../../../axios'
import history from '../../../history'

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {actions as UserAction} from '../../../reducers/user'

import './index.less'

class MyCategory extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            categories: []
        }
    }

    componentDidMount() {
        this.props.get_me()
        this.get_category()
    }

    onChange = (id) => {
        console.log(id)
        let newstate = this.state.categories.map( x => {
            if (x.id === id) {
                x.selected = !x.selected
            }
            return x
        })
        this.setState({categories: newstate})
    }

    get_category() {
        get('mem/project-category').then(resp => {
            let selected = this.props.userInfo.project_category,
                ids = selected.map(x => x.id)
            console.log(ids)
            
            this.setState({categories: resp.data.map(x=>{
                if (ids.includes(x.id)) {
                    x.selected = true
                }
                return x
            })});
        });
    }

    handOk = () => {
        let ids = []
        this.state.categories.map(x=>{
            if (x.selected) {
                ids.push(x.id)
            }
        })

        post(`mem/user-project-category`, {ids: ids.join(",")}).then(resp => {
            if (resp.success) {
                Toast.success('修改成功', 2)
                history.goBack()
            } else {
                Toast.fail(resp.msg, 2)
            }
        })
    }

    render() {
        const {categories} = this.state
        return (
            <div className="tag-container">
                {
                    categories.map(x => 
                        <Tag 
                            key={x.id} 
                            selected={x.selected}
                            onChange={()=>this.onChange(x.id)}
                        >
                            {x.name}
                        </Tag>
                    )
                }
                <div className="btns">
                    <a className="contact" onClick={()=>history.go(-1)}>返回</a>
                    <a className="contact" onClick={this.handOk}>确定</a>
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    return {
      userInfo: state.user.userInfo,
    }
}
  
function mapDispatchToProps(dispatch) {
    return  {
        get_me: bindActionCreators(UserAction.get_user_info, dispatch),
    }
}
  
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(MyCategory)